<?php
// https://leetcode-cn.com/problems/validate-ip-address/solution/yan-zheng-ip-di-zhi-by-leetcode/

class Solution {
    public function validateIPv4($IP)
    {
        // 以.为分隔符拆分
        $nums = explode('.', $IP);

        foreach ($nums as $x) {
          // Validate integer in range (0, 255):

          // 1. length of chunk is between 1 and 3
          // 校验每一部分长度为1到3
          if (strlen($x) == 0 || strlen($x) > 3) {
              return "Neither";
          }

          // 2. no extra leading zeros
          // 以0开头开始的  只能够长度为1  0.0.0.0 不能为192.01.2.1这种
          if (strpos($x, '0') === 0  && strlen($x) != 1) {
              return "Neither";
          }

          // 3. only digits are allowed
          // 验证每个字符是否为数字
          foreach (str_split($x, 1) as $ch) {
            if (! is_numeric($ch)) {
                return "Neither";
            }
          }

          // 4. less than 255
          // 是否超过255
          if (intval($x) > 255) {
              return "Neither";
          }
        }

        return "IPv4";
    }

    public function validateIPv6($IP)
    {
         // 以：为分隔符拆分
         $nums = explode(':', $IP);

         // 允许的字符表
         $hexdigits = array(
             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
             'a', 'b', 'c', 'd', 'e', 'f',
             'A', 'B', 'C', 'D', 'E', 'F'
         );

         foreach ($nums as $x) {
            // Validate hexadecimal in range (0, 2**16):

            // 1. at least one and not more than 4 hexdigits in one
            //  校验每一部分长度为1到4
            if (strlen($x) == 0 || strlen($x) > 4) {
                return "Neither";
            }

            // 2. only hexdigits are allowed: 0-9, a-f, A-F
            // 校验字符是否在允许的字符表中
             foreach (str_split($x, 1) as $ch) {
                if (! in_array($ch, $hexdigits, true)) {
                    return "Neither";
                }
            }
        }

        return "IPv6";
    }

  public function validIPAddress($IP) {
    if (count(explode('.', $IP)) == 4) {
        return $this->validateIPv4($IP);
    }

    if (count(explode(':', $IP)) == 8) {
        return $this->validateIPv6($IP);
    }

    return "Neither";
  }
}

var_dump((new Solution())->validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334"));